<template>
  <div class="block">
    <ele-form
      ref="eleForm"
      v-model="userProfile"
      :form-desc="formDesc"
      :request-fn="handleSubmit"
      :rules="rules"
      label-position="right"
      :is-loading="isLoading"
    />
  </div>
</template>

<script>
import api from '@/api/sys-user'
import { phone, email } from '@/utils/validator'
import { getToken } from '@/utils/auth'
import { config } from '@/utils/config'
import { mappingArray } from '@/utils/tools'
export default {
  props: {
    userProfile: {
      type: Object,
      default: () => {
        return {

        }
      }
    }
  },
  data() {
    return {
      isLoading: false,
      formDesc: {
        avatar: {
          type: 'image-uploader',
          label: '图片',
          multiple: true,
          attrs: {
            fileSize: 5,
            size: 80,
            action: config.uploadUrl,
            fileType: ['png', 'jpg', 'jpeg'],
            headers: {
              token: getToken()
            },
            responseFn(response, file) {
              return response.data.url
            }
          }
        },
        userName: {
          type: 'input',
          label: '用户名'
        },
        sex: {
          type: 'radio',
          label: '性别',
          options: async() => {
            const res = await api.sex()
            return mappingArray({ value: 'text', code: 'value' }, res.data)
          }
        },
        phoneNumber: {
          type: 'input',
          label: '手机号'
        },
        email: {
          type: 'input',
          label: '邮箱'
        }
      },
      rules: {
        userName: [
          { required: true, message: '用户名不能为空' }
        ],
        phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: phone, trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: email, trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleSubmit(data) {
      this.isLoading = true
      api.updateUserProfile(data).then(() => {
        this.$XModal.message({
          message: '信息更新成功',
          status: 'success'
        })
        this.isLoading = false
      }, () => {
        this.isLoading = false
      })
    }
  }
}
</script>
